import React from 'react'
import http from 'utils/http'
import NavHeader from 'common/NavHeader'
import styles from './index.module.scss'
import { Carousel, Flex, Modal, Toast } from 'antd-mobile'
import { BASE_URL } from 'utils/config'
import classNames from 'classnames'
import HousePackage from 'common/HousePackage'
import HouseItem from 'common/HouseItem'
import { hasToken } from 'utils/token'

const BMap = window.BMap

// 猜你喜欢
const recommendHouses = [
  {
    id: 1,
    houseImg: '/img/news/1.png',
    houseCode: '5cc44ed41439630e5b3d5f20',
    desc: '72.32㎡/南 北/低楼层',
    title: '安贞西里 3室1厅',
    price: 4500,
    tags: ['随时看房'],
  },
  {
    id: 2,
    houseImg: '/img/news/2.png',
    houseCode: '5cc44ed41439630e5b3d5f20',
    desc: '83㎡/南/高楼层',
    title: '天居园 2室1厅',
    price: 7200,
    tags: ['近地铁'],
  },
  {
    id: 3,
    houseImg: '/img/news/3.png',
    houseCode: '5cc44ed41439630e5b3d5f20',
    desc: '52㎡/西南/低楼层',
    title: '角门甲4号院 1室1厅',
    price: 4300,
    tags: ['集中供暖'],
  },
]

class Detail extends React.Component {
  state = {
    info: null,
    isLike: false,
  }
  async componentDidMount() {
    const id = this.props.match.params.id

    // 判断是否登录了, 如果登录了, 那么发送请求, 获取收藏isLike的状态
    if (hasToken()) {
      const resFav = await http.get(`/user/favorites/${id}`)
      this.setState({
        isLike: resFav.data.body.isFavorite,
      })
    }

    const res = await http.get(`/houses/${id}`)
    const { status, body } = res.data
    if (status === 200) {
      this.setState({
        info: body,
      })
      console.log(body)

      const { latitude, longitude } = body.coord
      const map = new BMap.Map('map')
      const point = new BMap.Point(longitude, latitude)
      map.centerAndZoom(point, 17)

      // 添加地图控件
      const label = new BMap.Label(
        `<span>${body.community}</span>
        <div class="mapArrow"></div>`,
        {
          position: point,
          offset: new BMap.Size(0, -36),
        }
      )

      label.setStyle({
        position: 'absolute',
        zIndex: -1,
        backgroundColor: 'rgb(238, 93, 91)',
        color: 'rgb(255, 255, 255)',
        height: 25,
        padding: '5px 10px',
        lineHeight: '14px',
        borderRadius: 3,
        boxShadow: 'rgb(204, 204, 204) 2px 2px 2px',
        whiteSpace: 'nowrap',
        fontSize: 12,
        userSelect: 'none',
      })
      map.addOverlay(label)
    }
  }

  handleLike = async () => {
    const id = this.props.match.params.id
    const { isLike } = this.state
    if (hasToken()) {
      // 登录了
      const method = isLike ? 'delete' : 'post'
      const res = await http[method](`/user/favorites/${id}`)
      const { status, description } = res.data
      if (status === 200) {
        Toast.success(description)
        this.setState({
          isLike: !isLike,
        })
      }
    } else {
      // 没登录, 提示未登录
      Modal.alert('温馨提示', '收藏商品, 需要先登录!', [
        { text: '取消' },
        { text: '去登录', onPress: () => this.props.history.push('/login') },
      ])
    }
  }

  render() {
    // 如果info数据还没有回来, 就先不渲染
    if (!this.state.info) return null
    const {
      community,
      houseImg,
      title,
      tags,
      price,
      roomType,
      oriented,
      size,
      floor,
      supporting,
      description,
    } = this.state.info
    console.log(this.state.info)
    return (
      <div className={styles.detail}>
        {/* 头部的导航 */}
        <NavHeader rightContent={<i className="iconfont icon-share"></i>}>
          {community}
        </NavHeader>

        {/* 轮播图 */}
        <Carousel autoplay={true} infinite className="slides">
          {houseImg.map((val) => (
            <a key={val} href="http://www.baidu.com">
              <img src={BASE_URL + val} alt="" />
            </a>
          ))}
        </Carousel>

        {/* 房屋基本信息 */}
        <div className="info">
          <h3 className="infoTitle">{title}</h3>
          <Flex className="tags">
            <Flex.Item>
              {tags.map((item, index) => {
                return (
                  <span
                    key={item}
                    className={classNames('tag', 'tag' + ((index % 3) + 1))}
                  >
                    {item}
                  </span>
                )
              })}
            </Flex.Item>
          </Flex>

          <Flex className="infoPrice">
            <Flex.Item className="infoPriceItem">
              <div>
                {price}
                <span className="month">/月</span>
              </div>
              <div>租金</div>
            </Flex.Item>
            <Flex.Item className="infoPriceItem">
              <div>{roomType}</div>
              <div>房型</div>
            </Flex.Item>
            <Flex.Item className="infoPriceItem">
              <div>{size}平米</div>
              <div>面积</div>
            </Flex.Item>
          </Flex>

          <Flex className="infoBasic" align="start">
            <Flex.Item>
              <div>
                <span className="title">装修：</span>
                精装
              </div>
              <div>
                <span className="title">楼层：</span>
                {floor}
              </div>
            </Flex.Item>
            <Flex.Item>
              <div>
                <span className="title">朝向：</span>
                {oriented.join('、')}
              </div>
              <div>
                <span className="title">类型：</span>普通住宅
              </div>
            </Flex.Item>
          </Flex>
        </div>

        {/* 地图位置 */}
        <div className="map">
          <div className="mapTitle">
            小区：
            <span>{community}</span>
          </div>
          <div className="mapContainer" id="map">
            地图
          </div>
        </div>

        {/* 配套设置 */}
        <div className="about">
          <div className="houseTitle">房屋配套</div>
          {supporting.length === 0 ? (
            <div className="titleEmpty">暂无数据</div>
          ) : (
            <HousePackage list={supporting} />
          )}
        </div>

        {/* 房屋概况 */}
        <div className="set">
          <div className="houseTitle">房源概况</div>
          <div>
            <div className="contact">
              <div className="user">
                <img src={BASE_URL + '/img/avatar.png'} alt="头像" />
                <div className="useInfo">
                  <div>王女士</div>
                  <div className="userAuth">
                    <i className="iconfont icon-auth" />
                    已认证房主
                  </div>
                </div>
              </div>
              <span className="userMsg">发消息</span>
            </div>

            <div className="descText">{description || '暂无房屋描述'}</div>
          </div>
        </div>

        {/* 推荐 */}
        <div className="recommend">
          <div className="houseTitle">猜你喜欢</div>
          <div className="items">
            {recommendHouses.map((item) => (
              <HouseItem item={item} key={item.id} />
            ))}
          </div>
        </div>

        {/* 底部收藏按钮 */}
        <Flex className="fixedBottom">
          <Flex.Item onClick={this.handleLike}>
            <img
              src={
                BASE_URL +
                (this.state.isLike ? '/img/star.png' : '/img/unstar.png')
              }
              className="favoriteImg"
              alt="收藏"
            />
            <span className="favorite">
              {this.state.isLike ? '已收藏' : '收藏'}
            </span>
          </Flex.Item>
          <Flex.Item>在线咨询</Flex.Item>
          <Flex.Item>
            <a href="tel:400-618-4000" className="telephone">
              电话预约
            </a>
          </Flex.Item>
        </Flex>
      </div>
    )
  }
}

export default Detail
